import html2Canvas from "html2canvas";
import JsPDF from "jspdf";

export default {
  install(Vue, options) {
    // 在 Vue.prototype.getPdf 定义中，返回 Promise
    Vue.prototype.getPdf = function (options = {}) {
      return new Promise((resolve, reject) => {
        const config = {
          download: true,
          format: "png",
          quality: 0.1,  //1.0最大
          ...options,
        };

        const title = this.htmlTitle || "document";

        html2Canvas(document.querySelector("#pdfDom"), {
          scale: 1,  //4最大
          allowTaint: true,
          useCORS: true,
          backgroundColor: null,
        })
          .then((canvas) => {
            const mimeType = config.format === "jpeg" ? "image/jpeg" : "image/png";
            const base64Image = canvas.toDataURL(mimeType, config.quality);

            // 保存到实例
            this.pdfBase64 = base64Image;

            // ========== 生成 PDF（如果需要下载）==========

            const contentWidth = canvas.width;
            const contentHeight = canvas.height;
            const pageHeight = (contentWidth / 592.28) * 841.89;
            const imgWidth = 595.28;
            const imgHeight = (592.28 / contentWidth) * contentHeight;

            const PDF = new JsPDF("", "pt", "a4");
            let position = 0;
            let leftHeight = contentHeight;

            if (leftHeight < pageHeight) {
              PDF.addImage(
                base64Image,
                config.format.toUpperCase(),
                0,
                0,
                imgWidth,
                imgHeight
              );
            } else {
              while (leftHeight > 0) {
                PDF.addImage(
                  base64Image,
                  config.format.toUpperCase(),
                  0,
                  position,
                  imgWidth,
                  imgHeight
                );
                leftHeight -= pageHeight;
                position -= 841.89;
                if (leftHeight > 0) PDF.addPage();
              }
            }
            var pdfBlob = PDF.output("blob");
            // console.log("pdf", pdfBlob);

            if (config.download) {
              PDF.save(title + ".pdf");
            }
            // ✅ 异步完成，resolve 出 Base64
            resolve(pdfBlob);
          })
          .catch((err) => {
            console.error("html2canvas error:", err);
            reject(err);
          });
      });
    };
  },
};
